#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Reflection;
using System.Windows.Forms;

using OshHost.Web;

namespace OshHost
{
	/// <summary>
	/// Summary description for Program.
	/// </summary>
	public class Program
	{
		private static bool _showErrors = true;

		public Program()
		{
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			try
			{
				// To proper initialize web configuration system WebHost's Initialize
				// method has to be called as early as possible
				WebHost.Current.Initialize();

				Application.EnableVisualStyles();
				Application.DoEvents();

				Application.ThreadException += 
					new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

				MainForm mainForm = new MainForm();
				Application.Run(mainForm);
			}
			catch(Exception e)
			{
				ProcessException(e);
			}
		}

		private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
		{
			try
			{
				ProcessException(e.Exception);
			}
			catch
			{
				Application.Exit();
			}
		}

		public static void ProcessException(Exception e)
		{
			ProcessException(e, true);
		}

		public static void ProcessException(Exception e, bool logException)
		{
			if(!Program.ShowErrors)
				return;

			if(logException)
				Osh.Log.Exception(Configuration.Local.HostTraceSource, e);

			lock(typeof(ExceptionForm))
			{
				ExceptionForm form = new ExceptionForm(e);
				form.ShowDialog();
			}
		}

		public static bool ShowErrors
		{
			get { return _showErrors; }
			set { _showErrors = value; }
		}
	}
}
